import { defineStore } from 'pinia'

const list = JSON.parse(localStorage.getItem('todos')) || []
const active = localStorage.getItem('active') || 'All'

const useTodosStore = defineStore('todo', {
    state: () => ({
        list,
        // name: '',
        filters: ['All', 'Active', 'Completed'],
        active
    }),

    actions: {
        changeDone (payload, id) {

            this.list.forEach(item => {
                if (item.id === id) {
                    item.done = payload
                }
            })

        },
        delTodo (id) {
            this.list = this.list.filter(item => item.id != id)
        },

        addTodo (payload) {
            const item = {
                id: Math.random(),
                name: payload,
                done: false
            }
            this.list.push(item)


        },
        // 全选的状态控制单选的状态
        checkAll (payload) {
            // alert(payload)
            this.list.forEach(item => {
                item.done = payload
            })
        },
        clearCompleted () {
            this.list = this.list.filter(item => !item.done)
        },

        changeActive (payload) {
            this.active = payload
        }


    },
    getters: {
        //  单选控制全选的状态
        isCheckAll () {
            // return true
            return this.list.every(item => item.done)
        },
        leftCount () {
            return this.list.filter(item => !item.done).length
        },


        // filters: ['All', 'Active', 'Completed'],
        showList () {
            if (this.active == 'All') {
                return this.list
            }
            if (this.active == 'Active') {
                return this.list.filter((item) => !item.done)
            }
            if (this.active == 'Completed') {
                return this.list.filter((item) => item.done)
            }
        }
    }

})


export default useTodosStore